import React, { useState, useEffect, useRef } from 'react';
import { ServiceStoragePieStyle } from './style';
import * as echarts from 'echarts/core';
import 'echarts-gl';
import { CommonArrType } from "@/services/types";
import { getFontSize } from '@/utils/tools/common';


type ServiceStoragePiePropsType = {
    title: string,
    percent: String,
    data: CommonArrType[]

};

const ServiceStoragePie: React.FC<ServiceStoragePiePropsType> = (props) => {
    const { title, percent,data } = props;
   
    // 颜色列表
    const colorList = ['#07D1FA', '#FFD15C'];

    // 生成扇形的曲面参数方程，用于 series-surface.parametricEquation
    function getParametricEquation(startRatio: any, endRatio: any, isSelected: any, isHovered: any, k: any, h: any) {

        // 计算

        const midRatio = (startRatio + endRatio) / 2;

        const startRadian = startRatio * Math.PI * 2;

        const endRadian = endRatio * Math.PI * 2;

        const midRadian = midRatio * Math.PI * 2;

        // 如果只有一个扇形，则不实现选中效果。

        if (startRatio === 0 && endRatio === 1) {

            isSelected = false;

        }

        // 通过扇形内径/外径的值，换算出辅助参数 k（默认值 1/3）

        k = 1;

        // 计算选中效果分别在 x 轴、y 轴方向上的位移（未选中，则位移均为 0）

        const offsetX = isSelected ? Math.cos(midRadian) * 0.1 : 0;

        const offsetY = isSelected ? Math.sin(midRadian) * 0.1 : 0;

        // 计算高亮效果的放大比例（未高亮，则比例为 1）

        const hoverRate = isHovered ? 1.05 : 1;

        // 返回曲面参数方程

        return {

            u: {

                min: -Math.PI,

                max: Math.PI * 3,

                step: Math.PI / 32,

            },

            v: {

                min: 0,

                max: Math.PI * 2,

                step: Math.PI / 20,

            },

            x: function (u: any, v: any) {

                if (u < startRadian) {

                    return offsetX + Math.cos(startRadian) * (1 + Math.cos(v) * k) * hoverRate;

                }

                if (u > endRadian) {

                    return offsetX + Math.cos(endRadian) * (1 + Math.cos(v) * k) * hoverRate;

                }

                return offsetX + Math.cos(u) * (1 + Math.cos(v) * k) * hoverRate;

            },

            y: function (u: any, v: any) {

                if (u < startRadian) {

                    return offsetY + Math.sin(startRadian) * (1 + Math.cos(v) * k) * hoverRate;

                }

                if (u > endRadian) {

                    return offsetY + Math.sin(endRadian) * (1 + Math.cos(v) * k) * hoverRate;

                }

                return offsetY + Math.sin(u) * (1 + Math.cos(v) * k) * hoverRate;

            },

            z: function (u: any, v: any) {

                if (u < -Math.PI * 0.5) {

                    return Math.sin(u);

                }

                if (u > Math.PI * 2.5) {

                    return Math.sin(u) * h * 0.1;

                }

                return Math.sin(v) > 0 ? 1 * h * 0.1 : -1;

            },

        };

    }
    // 生成模拟 3D 饼图的配置项
    function getPie3D(pieData: any, internalDiameterRatio: any) {
        let series = [];
        let sumValue = 0;
        let startValue = 0;
        let endValue = 0;
        let legendData = [];
        let k = typeof internalDiameterRatio !== 'undefined' ? (1 - internalDiameterRatio) / (1 + internalDiameterRatio) : 1 / 3;

        // 为每一个饼图数据，生成一个 series-surface 配置
        for (let i = 0; i < pieData.length; i++) {
            sumValue += pieData[i].value;

            let seriesItem: any = {
                name: typeof pieData[i].name === 'undefined' ? `series${i}` : pieData[i].name,
                type: 'surface',
                parametric: true,
                wireframe: {
                    show: false,
                },
                pieData: pieData[i],
                pieStatus: {
                    selected: false,
                    hovered: false,
                    k: 1 / 10,
                },
            };

            if (typeof pieData[i].itemStyle != 'undefined') {
                let itemStyle: any = {};

                typeof pieData[i].itemStyle.color != 'undefined' ? (itemStyle.color = pieData[i].itemStyle.color) : null;
                typeof pieData[i].itemStyle.opacity != 'undefined' ? (itemStyle.opacity = pieData[i].itemStyle.opacity) : null;

                seriesItem.itemStyle = itemStyle;
            }
            series.push(seriesItem);
        }

        // 使用上一次遍历时，计算出的数据和 sumValue，调用 getParametricEquation 函数，
        // 向每个 series-surface 传入不同的参数方程 series-surface.parametricEquation，也就是实现每一个扇形。
        for (let i = 0; i < series.length; i++) {
            endValue = startValue + series[i].pieData.value;
            series[i].pieData.startRatio = startValue / sumValue;
            series[i].pieData.endRatio = endValue / sumValue;
            series[i].parametricEquation = getParametricEquation(
                series[i].pieData.startRatio,
                series[i].pieData.endRatio,
                false,
                false,
                k,
                series[i].pieData.value
            );
            startValue = endValue;
            legendData.push(series[i].name);
        }
        series.push({
            name: 'mouseoutSeries',
            type: 'surface',
            parametric: true,
            wireframe: {
                show: false,
            },
            itemStyle: {
                opacity: 0.2,
                color: 'rgba(165, 247, 253, 1)',
            },
            parametricEquation: {
                u: {
                    min: 0,
                    max: Math.PI * 2,
                    step: Math.PI / 20,
                },
                v: {
                    min: 0,
                    max: Math.PI / 4,
                    step: Math.PI / 20,
                },
                x: function (u: any, v: any) {
                    return ((Math.sin(v) * Math.sin(u) + Math.sin(u)) / Math.PI) * 2.5;
                },
                y: function (u: any, v: any) {
                    return ((Math.sin(v) * Math.cos(u) + Math.cos(u)) / Math.PI) * 2.5;
                },
                z: function (u: any, v: any) {
                    return Math.cos(v) > 0 ? -3 : -3;
                },
            },
        });

        // 准备待返回的配置项，把准备好的 legendData、series 传入。
        let option = {
            backgroundColor: 'transparent',
            legend: {
                show: true,
                top: '2%',
                left: '22%',
                data: legendData,
                textStyle: {                            //图例文字的样式
                    color: '#fff',               //图例文字颜色
                    fontSize: getFontSize(16)                      //图例文字大小
                }
            },
            xAxis3D: {},
            yAxis3D: {},
            zAxis3D: {},
            grid3D: {
                viewControl: {
                    autoRotate: false, // 自动旋转
                },
                left: '28%',
                width: '32%',
                show: false,
                boxHeight: 20,
                // boxWidth和boxDepth这两个属性值保持一致，才可以在调整饼图宽度的时候保持水平，不然就会歪歪扭扭
                boxWidth: 110,
                boxDepth: 110,
            },
            series: series,
        };
        return option;
    }
    let chart: any = null;
    const chartRef = useRef(null);


    // 传入数据生成 option

    useEffect(() => {
        if (chartRef.current && data.length > 0) {
            // 创建一个echarts实例，返回echarts实例。不能在单个容器中创建多个echarts实例

            const serData = data.map((dItem, index) => {
                return {
                    ...dItem,
                    value: Number(dItem.number),
                    itemStyle: {
                        color: colorList[index],
                        fontSize: getFontSize(12),
                    },
                };
            });
            // 传入数据生成 option
            let option = getPie3D(serData, 0);
            option.series.push({
                name: 'pie2d',
                type: 'pie',
                label: {
                    formatter: (params: any) => {
                        console.log(params)
                        
                        return `{d|${params.name == "未使用" ? '服务器未使用率' : '服务器使用率'}} \n {${params.color == "#FFD15C" ? 'b' : 'c'}|${params.percent}%}`
                    },
                    opacity: 1,
                    fontSize: getFontSize(14),
                    lineHeight: getFontSize(20),
                    rich: {
                        d: {
                            color: '#ddd',
                            fontSize: getFontSize(10),
                            lineHeight: getFontSize(24),
                            height: getFontSize(24),
                            width: getFontSize(20),
                            align: 'center',
                        },
                        b: {
                            color: "#FFD15C",
                            fontSize: getFontSize(24),
                            lineHeight: getFontSize(20),
                            align: 'center',
                            width: getFontSize(20),
                        },
                        c: {
                            color: "#07D1FA",
                            fontSize: getFontSize(24),
                            lineHeight: getFontSize(20),
                            align: 'center',
                            width: getFontSize(20),
                        }
                    },
                },
                labelLine: {
                    length: getFontSize(60),
                    length2: getFontSize(60),
                    lineStyle: {
                        width: getFontSize(1),
                    },
                },

                startAngle: 60, //起始角度，支持范围[0, 360]。 
                clockwise: false, //饼图的扇区是否是顺时针排布。上述这两项配置主要是为了对齐3d的样式 
                radius: ['10%', '10%'],
                center: ['45%', '50%'],
                data: serData,
                itemStyle: {
                    opacity: 0,
                },

            });
            chart = echarts.init(chartRef.current, null, {});
            option && chart.setOption(option);
        }

        // 组件卸载
        return () => {
            // chart.dispose() 销毁实例。实例销毁后无法再被使用
            if (chart) {
                chart.dispose();
            }
        };
    }, [data]);
    return (
        <ServiceStoragePieStyle>
            <div className='dpiebox-container' style={{ backgroundColor: 'rgba(0, 0, 0, 0)' }}>
                <div className='dpiebox'>
                </div>
                <div ref={chartRef} style={{ width: '100%', height: '13vw', backgroundColor: 'rgba(1, 20, 67, 1)' }}>
                </div>
            </div>

        </ServiceStoragePieStyle>
    );
};

export default ServiceStoragePie;
